<template>
  <div>
    <!-- {{ checkDetailForm.projectList }} -->
    <component
      v-for="item in sortedComponents"
      :key="item.regionId + item.titel"
      :id="`anchor-${item.regionId}`"
      :is="item.component"
      :title="item.titel"
      :regionId="item.regionId"
      :region_data_pointer="props.region_data_pointer"
      v-model="focusElement"
      dbClickPlaceholder="可双击编辑"
      @handleDbClickFocus="handleDbClickFocus"
      @handleDbClickBlur="handleDbClickBlur"
      class="py-[0.001rem] box-border"
    />
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { watchStorage, setStorageWithEvent } from "@/utils/GlobalMonitoring.js";

import VisualChart from "./component/VisualChart.vue";
import ComputerOptometry from "./component/ComputerOptometry.vue";
import SubjectiveRefraction from "./component/SubjectiveRefraction.vue";
import IntraocularTension from "./component/IntraocularTension.vue";
import BioMeasurement from "./component/BioMeasurement.vue";
import OptometristQuery from "./component/OptometristQuery.vue";
import VisualFunctionNiu from "./component/VisualFunction_niu.vue";

import { handleApiResponse } from "@/utils/request.js";
import { UpdateRegionResult } from "../../../../../../wailsjs/go/api/ReportApi";

onMounted(() => {});
const props = defineProps({
  region_data_pointer: {
    type: Object,
    default: () => {},
  },
  checkId: {
    type: Number,
    default: -1,
  },
});

const userStore = useUserStore();
const { cutStatus, flowActiveIndex, checkDetailForm } = storeToRefs(userStore);

let components = [
  {
    regionId: 1,
    sort: 0,
    titel: "视力表",
    isChecked: true,
    component: VisualChart,
  },
  {
    regionId: 2,
    sort: 0,
    titel: "电脑验光",
    isChecked: true,
    component: ComputerOptometry,
  },
  { regionId: 3, sort: 0, titel: "眼压", component: IntraocularTension },
  {
    regionId: 4,
    sort: 0,
    titel: "生物测量",
    isChecked: true,
    component: BioMeasurement,
  },
  {
    regionId: 5,
    sort: 0,
    titel: "主观验光",
    isChecked: true,
    component: SubjectiveRefraction,
  },
  {
    regionId: 7,
    sort: 0,
    titel: "配镜参数",
    isChecked: true,
    component: OptometristQuery,
  },
  {
    regionId: 8,
    sort: 0,
    titel: "视功能(牛眼)",
    isChecked: true,
    component: VisualFunctionNiu,
  },
];

const sortedComponents = computed(() => {
  return components
    .sort((a, b) => a.regionId - b.regionId)
    .filter((item) => {
      if (checkDetailForm.value?.projectList?.length > 0)
        checkDetailForm.value.projectList.forEach((e) => {
          if (e.regionId === item.regionId) {
            item.isChecked = e.isChecked;
          }
        });
      return item.isChecked;
    });
});

const regionData = ref([]); // 区域数据点

// 双击之后需要获取焦点的DOM元素
const focusElement = ref("");
const handleDbClickFocus = (field) => {
  focusElement.value = field;
};
// 失去焦点
const handleDbClickBlur = (data) => {
  focusElement.value = "";

  let form = {};
  // 只更改对应区域的数据点
  let foundData = regionData.value.find(
    (item) => item.regionId === data.regionId
  );
  foundData.regionResult = JSON.stringify(data.data);

  if (props.checkId == -1) {
    form = {
      name: checkDetailForm.value.relationName || "",
      customRelativeId: checkDetailForm.value.relationId || null,
      customId: checkDetailForm.value.customerId || null,
      phone: checkDetailForm.value.phone || "",
      age: checkDetailForm.value.age || null,
      sex: checkDetailForm.value.sex || null,
      listId: checkDetailForm.value.id,
      listCode: checkDetailForm.value.code,
      scan: `{type=inspect&&listId=${checkDetailForm.value.id}&&birthday=${checkDetailForm.value.birthday}&&archivesCode=${checkDetailForm.value.medicalCardNumber}&&code=${checkDetailForm.value.code}&&name=${checkDetailForm.value.relationName}&&phone=${checkDetailForm.value.phone}&&sex=${checkDetailForm.value.sex}&&age=${checkDetailForm.value.age}}`,
    };
  }

  // return ElMessage.warning("修改数据点正在紧急开发中...");
  handleApiResponse(() =>
    UpdateRegionResult({
      ...form,
      dataPayload: [foundData],
    })
  ).then((res) => {
    if (res.code == 0) {
      ElMessage.success("保存成功");
    }
  });
};
let cleanup;
onMounted(() => {
  cleanup = watchStorage("refresh_region_data", (e) => {
    regionData.value = e.data.regionData;
  });

  // 组件卸载时清理监听
  return () => cleanup();
});

onBeforeUnmount(() => {
  cleanup();
});

let cleanup2;
onMounted(() => {
  cleanup2 = watchStorage("anchor_jump", (e) => {
    const anchor = document.getElementById(`anchor-${e.data.elementId}`);

    if (anchor) {
      anchor.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    }
  });

  // 组件卸载时清理监听
  return () => cleanup();
});

onBeforeUnmount(() => {
  cleanup2();
});
</script>

<style scoped lang="scss">
</style>